package day03;

import util.JdbcUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class DataBaseQueryer {

    private JFrame jf;
    private JLabel jl;
    private JTextField jtf;
    private JButton jb;

    public DataBaseQueryer() {
        jf=new JFrame("数据库查询器");
        jl=new JLabel("查询语句");
        jtf=new JTextField(40);
        jb=new JButton("查询");
    }

    private void init(){
        JPanel jp=new JPanel();
        jp.add(jl);
        jp.add(jtf);
        jp.add(jb);

        jf.add(jp, BorderLayout.NORTH);
    }

    private void addEventHandler(){
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                query();
            }
        });

        jtf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                query();
            }
        });
    }

    private void query(){

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=jtf.getText();

            ps=con.prepareStatement(sql);


            rs=ps.executeQuery();


            DefaultTableModel dtm=new DefaultTableModel();

            ResultSetMetaData rsmd=rs.getMetaData();

            int columnCount=rsmd.getColumnCount();

            System.out.println("columnCount = " + columnCount);

            for (int i = 0; i < columnCount; i++) {
                String columnName=rsmd.getColumnName(i+1);
                System.out.println("columnName = " + columnName);
                dtm.addColumn(columnName);
            }

            while(rs.next()){
                Vector<String> rowData=new Vector<>();
                for (int i = 0; i < columnCount; i++) {
                    rowData.add(rs.getString(i+1));
                }
                dtm.addRow(rowData);
            }

            JTable jt=new JTable(dtm);

            JScrollPane jsp=new JScrollPane(jt);

            jf.add(jsp);

            jf.setVisible(true);



            con.commit();
        }catch (Exception e){
            JOptionPane.showMessageDialog(jf,e.toString());
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

    }

    public void show(){
        init();
        addEventHandler();
        jf.setSize(600,400);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new DataBaseQueryer().show();
    }



}
